import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'message_center_logic.dart';

/// 消息中心页面
class MessageCenterView extends GetView<MessageCenterLogic> {
  const MessageCenterView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.white, size: 20.sp),
          onPressed: () => Get.back(),
        ),
        title: Text(
          '消息中心',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          // Tab栏
          _buildTabBar(),
          // Tab内容
          Expanded(
            child: Obx(() => IndexedStack(
                  index: controller.state.currentTabIndex.value,
                  children: [
                    _buildSystemNotifications(),
                    _buildHealthAlerts(),
                    _buildFamilyApplications(),
                  ],
                )),
          ),
        ],
      ),
    );
  }

  /// Tab栏
  Widget _buildTabBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildTab('系统通知', 0, controller.state.systemNotificationCount.value),
          SizedBox(width: 24.w),
          _buildTab('健康警报', 1, controller.state.healthAlertCount.value),
          SizedBox(width: 24.w),
          _buildTab('家庭圈申请', 2, controller.state.familyApplicationCount.value),
        ],
      ),
    );
  }

  /// 单个Tab
  Widget _buildTab(String title, int index, int count) {
    return Obx(() {
      final isSelected = controller.state.currentTabIndex.value == index;
      return GestureDetector(
        onTap: () => controller.changeTab(index),
        child: Column(
          children: [
            Row(
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight:
                        isSelected ? FontWeight.w600 : FontWeight.normal,
                    color: isSelected ? Colors.white : Colors.grey[500],
                  ),
                ),
                if (count > 0) ...[
                  SizedBox(width: 6.w),
                  Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                    decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    child: Text(
                      count.toString(),
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ],
            ),
            SizedBox(height: 8.h),
            Container(
              height: 2.h,
              width: 40.w,
              decoration: BoxDecoration(
                color: isSelected ? Colors.white : Colors.transparent,
                borderRadius: BorderRadius.circular(1.r),
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 系统通知列表
  Widget _buildSystemNotifications() {
    return Obx(() {
      if (controller.state.systemNotifications.isEmpty) {
        return _buildEmptyState('暂无系统通知');
      }
      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
        itemCount: controller.state.systemNotifications.length,
        itemBuilder: (context, index) {
          final notification = controller.state.systemNotifications[index];
          return _buildNotificationCard(
            title: notification['title'] ?? '',
            content: notification['content'] ?? '',
            time: notification['time'] ?? '',
            isRead: notification['isRead'] ?? false,
            noticeId: notification['noticeId'],
          );
        },
      );
    });
  }

  /// 健康警报列表
  Widget _buildHealthAlerts() {
    return Obx(() {
      if (controller.state.healthAlerts.isEmpty) {
        return _buildEmptyState('暂无健康警报');
      }
      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
        itemCount: controller.state.healthAlerts.length,
        itemBuilder: (context, index) {
          final alert = controller.state.healthAlerts[index];
          return _buildNotificationCard(
            title: alert['title'] ?? '',
            content: alert['content'] ?? '',
            time: alert['time'] ?? '',
            isRead: alert['isRead'] ?? false,
          );
        },
      );
    });
  }

  /// 家庭圈申请列表
  Widget _buildFamilyApplications() {
    return Obx(() {
      if (controller.state.familyApplications.isEmpty) {
        return _buildEmptyState('暂无家庭圈申请');
      }
      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
        itemCount: controller.state.familyApplications.length,
        itemBuilder: (context, index) {
          final application = controller.state.familyApplications[index];
          final joinType = application['joinType'] ?? '2';
          final isCreator = application['isCreator'] ?? false;

          // 根据角色和加入类型确定显示文本和显示的用户名
          String joinTypeText;
          bool canApprove = false;
          String displayName;

          if (isCreator) {
            // 我是群主
            if (joinType == '1') {
              // 我邀请别人
              joinTypeText = '邀请加入';
              canApprove = false; // 只看状态
              displayName = application['applicantName'] ?? '未知用户'; // 显示被邀请人
            } else {
              // 别人申请加入我的群
              joinTypeText = '申请加入';
              canApprove = true; // 我需要审核
              displayName = application['applicantName'] ?? '未知用户'; // 显示申请人
            }
          } else {
            // 我是成员
            if (joinType == '1') {
              // 别人邀请我
              joinTypeText = '邀请加入';
              canApprove = true; // 我需要审核
              displayName = application['groupCreator'] ?? '未知用户'; // 显示群主（邀请人）
            } else {
              // 我申请加入别人的群
              joinTypeText = '申请加入';
              canApprove = false; // 只看状态
              displayName = application['groupCreator'] ?? '未知用户'; // 显示群主
            }
          }

          return _buildApplicationCard(
            applicationId: application['id'],
            applicantId: application['applicantId'],
            userName: displayName,
            groupName: application['groupName'] ?? '未命名群组',
            groupCode: application['groupCode'] ?? '',
            time: application['applicantTime'] ?? '',
            approvalState: application['approvalState'] ?? '1',
            joinTypeText: joinTypeText,
            canApprove: canApprove,
            isCreator: isCreator,
          );
        },
      );
    });
  }

  /// 通知卡片
  Widget _buildNotificationCard({
    required String title,
    required String content,
    required String time,
    required bool isRead,
    int? noticeId,
  }) {
    return GestureDetector(
      onTap: () async {
        if (noticeId != null) {
          final detail = await controller.viewNotificationDetail(noticeId);
          if (detail != null) {
            // 可以在这里显示详情对话框或跳转到详情页
            _showNotificationDetail(detail);
          }
        }
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 12.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: isRead ? Colors.grey[900] : Colors.grey[850],
          borderRadius: BorderRadius.circular(12.r),
          border: isRead ? null : Border.all(
            color: Colors.orange.withOpacity(0.3),
            width: 1,
          ),
        ),
        child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图标
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Icon(
              Icons.notifications,
              color: Colors.grey[400],
              size: 20.sp,
            ),
          ),
          SizedBox(width: 12.w),
          // 内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 6.h),
                Text(
                  content,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                    height: 1.4,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(height: 8.h),
                Text(
                  time,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(width: 12.w),
          // 右侧状态标签
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: isRead ? Colors.grey[800] : Colors.orange.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border.all(
                    color: isRead ? Colors.grey[700]! : Colors.orange,
                    width: 1,
                  ),
                ),
                child: Text(
                  isRead ? '已读' : '未读',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: isRead ? Colors.grey[500] : Colors.orange,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              if (!isRead) ...[
                SizedBox(height: 4.h),
                Container(
                  width: 8.w,
                  height: 8.w,
                  decoration: const BoxDecoration(
                    color: Colors.red,
                    shape: BoxShape.circle,
                  ),
                ),
              ],
            ],
          ),
        ],
      ),
      ),
    );
  }

  /// 申请卡片
  Widget _buildApplicationCard({
    required int applicationId,
    required int applicantId,
    required String userName,
    required String groupName,
    required String groupCode,
    required String time,
    required String approvalState,
    required String joinTypeText,
    required bool canApprove,
    required bool isCreator,
  }) {
    // 根据审批状态显示不同的文本
    String getStatusText() {
      if (approvalState == '1') {
        return canApprove ? '待审核' : '待同意';
      } else if (approvalState == '2') {
        return '已通过';
      } else if (approvalState == '3') {
        return '已拒绝';
      }
      return '未知';
    }

    // 根据审批状态显示不同的颜色
    Color getStatusColor() {
      if (approvalState == '1') {
        return Colors.orange;
      } else if (approvalState == '2') {
        return Colors.green;
      } else if (approvalState == '3') {
        return Colors.red;
      }
      return Colors.grey;
    }

    return GestureDetector(
      onTap: () async {
        // 只有待审核且有审核权限的才能跳转详情页
        if (approvalState == '1' && canApprove) {
          final result = await Get.toNamed('/application-detail', arguments: {
            'applicationId': applicationId,
            'applicantId': applicantId,
            'userName': userName,
            'groupName': groupName,
            'groupCode': groupCode,
            'time': time,
            'approvalState': approvalState,
            'joinTypeText': joinTypeText,
            'canApprove': canApprove,
            'isCreator': isCreator,
          });

          // 如果处理了申请，刷新列表
          if (result == true) {
            controller.refresh();
          }
        }
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 12.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.grey[900],
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头像
            Container(
              width: 50.w,
              height: 50.w,
              decoration: BoxDecoration(
                color: Colors.grey[800],
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.person,
                color: Colors.grey[400],
                size: 24.sp,
              ),
            ),
            SizedBox(width: 12.w),
            // 内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    userName,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    joinTypeText == '邀请加入'
                        ? (isCreator ? '邀请TA加入"$groupName"' : '邀请你加入"$groupName"')
                        : (isCreator ? '申请加入"$groupName"' : '申请加入"$groupName"'),
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[400],
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    time,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            // 状态按钮
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                color: approvalState == '1'
                    ? getStatusColor().withOpacity(0.2)
                    : Colors.grey[800],
                borderRadius: BorderRadius.circular(16.r),
                border: approvalState == '1'
                    ? Border.all(color: getStatusColor(), width: 1)
                    : null,
              ),
              child: Text(
                getStatusText(),
                style: TextStyle(
                  fontSize: 12.sp,
                  color: approvalState == '1'
                      ? getStatusColor()
                      : Colors.grey[500],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 空状态
  Widget _buildEmptyState(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 80.sp,
            color: Colors.grey[700],
          ),
          SizedBox(height: 20.h),
          Text(
            message,
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  /// 显示通知详情对话框
  void _showNotificationDetail(Map<String, dynamic> detail) {
    Get.dialog(
      Dialog(
        backgroundColor: Colors.grey[900],
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(24.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              Row(
                children: [
                  Expanded(
                    child: Text(
                      detail['title'] ?? '通知详情',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.close, color: Colors.grey[400]),
                    onPressed: () => Get.back(),
                  ),
                ],
              ),
              SizedBox(height: 16.h),
              // 时间
              Text(
                detail['createTime'] ?? '',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[500],
                ),
              ),
              SizedBox(height: 16.h),
              // 内容
              Text(
                detail['content'] ?? '',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[300],
                  height: 1.5,
                ),
              ),
              SizedBox(height: 24.h),
              // 确定按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Get.back(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    padding: EdgeInsets.symmetric(vertical: 12.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                  child: Text(
                    '知道了',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
